<template>
  <view class="canvas-container">
    <!-- Canvas画布区域 -->
    <view class="canvas-wrapper">
      <canvas
        id="textCanvas"
        type="2d"
        canvas-id="textCanvas"
        :style="{
                    width: canvasWidth + 'px',
                    height: canvasHeight + 'px',
                }"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      ></canvas>
    </view>

    <!-- 控制面板 -->
    <view class="control-panel">
      <!-- 文字内容输入 -->
      <view class="control-group">
        <text class="control-label">文字内容:</text>
        <input
          v-model="textContent"
          class="text-input"
          placeholder="请输入文字内容"
          @input="updateText"
        />
      </view>

      <!-- 字体样式控制 -->
      <view class="control-group">
        <text class="control-label">字体样式:</text>
        <view class="button-group">
          <button
            :class="['style-btn', textStyle.bold ? 'active' : '']"
            @click="toggleStyle('bold')"
          >
            加粗
          </button>
          <button
            :class="['style-btn', textStyle.italic ? 'active' : '']"
            @click="toggleStyle('italic')"
          >
            斜体
          </button>
          <button
            :class="[
                            'style-btn',
                            textStyle.underline ? 'active' : '',
                        ]"
            @click="toggleStyle('underline')"
          >
            下划线
          </button>
        </view>
      </view>

      <!-- 字体大小控制 -->
      <view class="control-group">
        <text class="control-label">字体大小:</text>
        <view class="slider-group">
          <slider
            show-value
            :value="textStyle.fontSize"
            min="12"
            max="72"
            @change="onFontSizeChange"
          />
        </view>
      </view>

      <!-- 颜色选择 -->
      <view class="control-group">
        <text class="control-label">文字颜色:</text>
        <view class="color-picker">
          <view
            v-for="color in colorOptions"
            :key="color"
            :class="[
                            'color-option',
                            textStyle.color === color ? 'active' : '',
                        ]"
            :style="{ backgroundColor: color }"
            @click="setTextColor(color)"
          ></view>
        </view>
      </view>

      <!-- 间距控制 -->
      <view class="control-group">
        <text class="control-label">字间距:</text>
        <view class="slider-group">
          <slider
            show-value
            :value="textStyle.letterSpacing"
            min="0"
            max="20"
            @change="onLetterSpacingChange"
          />
        </view>
      </view>

      <!-- 行高控制 -->
      <view class="control-group">
        <text class="control-label">行高:</text>
        <view class="slider-group">
          <slider
            show-value
            :value="textStyle.lineHeight"
            min="1"
            max="3"
            step="0.1"
            @change="onLineHeightChange"
          />
        </view>
      </view>

      <!-- 布局方向 -->
      <view class="control-group">
        <text class="control-label">排列方向:</text>
        <view class="button-group">
          <button
            :class="[
                            'layout-btn',
                            textStyle.direction === 'horizontal'
                                ? 'active'
                                : '',
                        ]"
            @click="setLayoutDirection('horizontal')"
          >
            横向排列
          </button>
          <button
            :class="[
                            'layout-btn',
                            textStyle.direction === 'vertical' ? 'active' : '',
                        ]"
            @click="setLayoutDirection('vertical')"
          >
            纵向排列
          </button>
        </view>
      </view>

      <!-- 缩放控制 -->
      <view class="control-group">
        <text class="control-label">缩放:</text>
        <view class="zoom-controls">
          <button class="zoom-btn" @click="zoomOut">缩小</button>
          <text class="zoom-value"
          >{{ (textStyle.scale * 100).toFixed(0) }}%</text
          >
          <button class="zoom-btn" @click="zoomIn">放大</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';

// Canvas尺寸
const canvasWidth = ref(300);
const canvasHeight = ref(400);

// 文字内容
const textContent = ref('Hello Canvas');

// 文字样式配置
const textStyle = reactive({
  fontSize: 24,
  color: '#000000',
  bold: false,
  italic: false,
  underline: false,
  letterSpacing: 0,
  lineHeight: 1.5,
  direction: 'horizontal' as 'horizontal' | 'vertical',
  scale: 1,
  x: 50,
  y: 100,
});

// 颜色选项
const colorOptions = ref([
  '#000000',
  '#FF0000',
  '#00FF00',
  '#0000FF',
  '#FFFF00',
  '#FF00FF',
  '#00FFFF',
  '#FFA500',
]);

// Canvas上下文
let ctx: any = null;

onMounted(() => {
  nextTick(() => {
    initCanvas();
  });
});

// 初始化Canvas
const initCanvas = () => {
  const query = uni.createSelectorQuery();
  query
    .select('#textCanvas')
    .fields({ node: true, size: true })
    .exec((res) => {
      if (res[0]) {
        const canvas = res[0].node;
        ctx = canvas.getContext('2d');
        drawText();
      }
    });
};

// 绘制文字
const drawText = () => {
  if (!ctx) return;

  // 清空画布
  ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value);

  // 设置文字样式
  let fontStyle = `${textStyle.bold ? 'bold ' : ''}${textStyle.italic ? 'italic ' : ''}`;
  fontStyle += `${textStyle.fontSize * textStyle.scale}px Arial`;

  ctx.font = fontStyle;
  ctx.fillStyle = textStyle.color;
  ctx.textBaseline = 'top';
  ctx.letterSpacing = `${textStyle.letterSpacing}px`;

  // 绘制文字
  if (textStyle.direction === 'horizontal') {
    // 横向排列
    ctx.fillText(textContent.value, textStyle.x, textStyle.y);

    // 绘制下划线
    if (textStyle.underline) {
      const textWidth = ctx.measureText(textContent.value).width;
      ctx.beginPath();
      ctx.moveTo(
        textStyle.x,
        textStyle.y + textStyle.fontSize * textStyle.scale + 2,
      );
      ctx.lineTo(
        textStyle.x + textWidth,
        textStyle.y + textStyle.fontSize * textStyle.scale + 2,
      );
      ctx.strokeStyle = textStyle.color;
      ctx.stroke();
    }
  } else {
    // 纵向排列（每个字符单独绘制）
    const chars = textContent.value.split('');
    let currentY = textStyle.y;
    chars.forEach((char) => {
      ctx.fillText(char, textStyle.x, currentY);
      currentY +=
        textStyle.fontSize * textStyle.scale * textStyle.lineHeight;
    });
  }

  // // 更新Canvas
  // ctx.draw();
};

// 更新文字内容
const updateText = () => {
  drawText();
};

// 切换文字样式
const toggleStyle = (style: 'bold' | 'italic' | 'underline') => {
  textStyle[style] = !textStyle[style];
  drawText();
};

// 字体大小变化
const onFontSizeChange = (e: any) => {
  textStyle.fontSize = e.detail.value;
  drawText();
};

// 字间距变化
const onLetterSpacingChange = (e: any) => {
  textStyle.letterSpacing = e.detail.value;
  drawText();
};

// 行高变化
const onLineHeightChange = (e: any) => {
  textStyle.lineHeight = e.detail.value;
  drawText();
};

// 设置文字颜色
const setTextColor = (color: string) => {
  textStyle.color = color;
  drawText();
};

// 设置布局方向
const setLayoutDirection = (direction: 'horizontal' | 'vertical') => {
  textStyle.direction = direction;
  drawText();
};

// 放大
const zoomIn = () => {
  textStyle.scale = Math.min(textStyle.scale + 0.1, 3);
  drawText();
};

// 缩小
const zoomOut = () => {
  textStyle.scale = Math.max(textStyle.scale - 0.1, 0.5);
  drawText();
};

// 触摸事件处理（用于移动文字位置）
let isDragging = false;
let startX = 0;
let startY = 0;

const handleTouchStart = (e: any) => {
  isDragging = true;
  startX = e.touches[0].clientX;
  startY = e.touches[0].clientY;
};

const handleTouchMove = (e: any) => {
  if (!isDragging) return;

  const currentX = e.touches[0].clientX;
  const currentY = e.touches[0].clientY;

  const deltaX = currentX - startX;
  const deltaY = currentY - startY;

  textStyle.x += deltaX;
  textStyle.y += deltaY;

  startX = currentX;
  startY = currentY;

  drawText();
};

const handleTouchEnd = () => {
  isDragging = false;
};
</script>

<style scoped lang="scss">
.canvas-container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.canvas-wrapper {
  flex: 1;
  border: 2rpx solid #e0e0e0;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  background-color: #f9f9f9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.control-panel {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.control-group {
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
}

.control-label {
  width: 150rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.text-input {
  flex: 1;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 28rpx;
}

.button-group {
  flex: 1;
  display: flex;
  gap: 10rpx;
}

.style-btn,
.layout-btn {
  flex: 1;
  font-size: 24rpx;
  padding: 16rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #fff;

  &.active {
    background-color: #007aff;
    color: #fff;
    border-color: #007aff;
  }
}

.slider-group {
  flex: 1;
}

.color-picker {
  flex: 1;
  display: flex;
  gap: 10rpx;
  flex-wrap: wrap;
}

.color-option {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
  border: 2rpx solid #e0e0e0;

  &.active {
    border-color: #007aff;
    border-width: 4rpx;
  }
}

.zoom-controls {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.zoom-btn {
  padding: 16rpx 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #fff;
  font-size: 24rpx;
}

.zoom-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  min-width: 100rpx;
  text-align: center;
}
</style>
